package com.jtpay.payresulthelper.http.retrofit;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jtpay.payresulthelper.http.JsonConver.JsonConverterFactory;
import com.jtpay.payresulthelper.http.JsonConver.ToStringConverterFactory;
import com.jtpay.payresulthelper.http.interceptor.HttpCacheInterceptor;
import com.jtpay.payresulthelper.http.interceptor.LoggerInterceptor;
import com.jtpay.payresulthelper.util.ApiConstant;
import com.jtpay.payresulthelper.util.LogUtil;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * File: RetrofitServiceManager.java
 * Author: Administrator
 * Create: 2018/07/30 09:37
 */
public class RetrofitServiceManager {
    private Retrofit.Builder mBuilder;

    public enum RetrofitBuilderEnum {
        JSON,
        NORMAL,
        CUSTOM,
    }

    RetrofitServiceManager(RetrofitBuilderEnum builderEnum) {
        switch (builderEnum) {
            case JSON:
                initJsonRetrofit();
                break;
            case CUSTOM:
                initCustomRetrofit();
                break;
            case NORMAL:
                initRetrofit();
                break;
        }
    }

    private void initJsonRetrofit() {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
//                .addConverterFactory(GsonConverterFactory.create(gson))
//                .addConverterFactory(JsonConverterFactory.create())
        mBuilder = new Retrofit.Builder()
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(ApiConstant.getUrl());
    }

    private void initRetrofit() {
//                .addConverterFactory(JsonConverterFactory.create())
        mBuilder = new Retrofit.Builder()
                .client(getOkHttpClient())
                .addConverterFactory(new ToStringConverterFactory())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(ApiConstant.getUrl());
    }

    private void initCustomRetrofit() {
        mBuilder = new Retrofit.Builder()
                .client(getOkHttpClient())
                .addConverterFactory(JsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(ApiConstant.getUrl());
    }

    private OkHttpClient getOkHttpClient() {
        return new OkHttpClient.Builder()
                .readTimeout(ApiConstant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(ApiConstant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(ApiConstant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(getLoggerInterceptor())
                .addNetworkInterceptor(new HttpCacheInterceptor())
                .build();
    }

    private OkHttpClient getOkHttpClient(long timeout) {
        return new OkHttpClient.Builder()
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .addInterceptor(getLoggerInterceptor())
                .addNetworkInterceptor(new HttpCacheInterceptor())
                .build();
    }

    private Interceptor getLoggerInterceptor() {
        //   日志拦截器
        LoggerInterceptor interceptor = new LoggerInterceptor(new LoggerInterceptor.Logger() {
            @Override
            public void log(String message) {
                try {
                    String text = URLDecoder.decode(message, "utf-8");
                    LogUtil.log("OKHttp-----" + text);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    LogUtil.log("OKHttp-----" + message);
                }
            }
        });
        interceptor.setLevel(LoggerInterceptor.Level.BASIC);
        return interceptor;
    }


    public void setBaseUrl(String baseUrl) {
        this.mBuilder.baseUrl(baseUrl);
    }

    public void setHttpTimeout(long timeout) {
        mBuilder.client(getOkHttpClient(timeout));
    }

    private static class SingletonJsonHolder {
        private static final RetrofitServiceManager INSTANCE =
                new RetrofitServiceManager(RetrofitBuilderEnum.JSON);
    }

    private static class SingletonHolder {
        private static final RetrofitServiceManager INSTANCE =
                new RetrofitServiceManager(RetrofitBuilderEnum.NORMAL);
    }

    /**
     * 获取RetrofitServiceManager
     *
     * @return RetrofitServiceManager
     */
    public static RetrofitServiceManager getJsonInstance() {
        return SingletonJsonHolder.INSTANCE;
    }

    public static RetrofitServiceManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>     class
     * @return <T>
     */
    public <T> T create(Class<T> service) {
//        return mRetrofit.create(service);
        return mBuilder.build().create(service);
    }
}
